package org.kanstantin.nwscan.crawler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * @author kanstantin
 */
public class ResultsContainerImpl implements ResultsContainer {
	private List<SearchResult> resultList = getNewList();
	private int maxListSize = 10000;
	private ResultsWritable resultsWriter;

	private List getNewList() {
		List<SearchResult> r = Collections.synchronizedList(new ArrayList<SearchResult>());
		return r;
	}

	@Override
	public void addResult(SearchResult result) {
		resultList.add(result);
		if (resultList.size() > maxListSize) {
			synchronized(ResultsContainerImpl.class) {
				Thread t = new Thread(new ResultDumper(resultList));
				resultList = getNewList();
				t.start();
			}
		}
	}

	public void setResultsWriter(ResultsWritable resultsWriter) {
		this.resultsWriter = resultsWriter;
	}

	class ResultDumper implements Runnable {
		private List<SearchResult> dumpingList;

		ResultDumper(List<SearchResult> queue) {
			this.dumpingList = queue;
		}

		@Override
		public void run() {
			resultsWriter.save(dumpingList);
		}
	}
}
